﻿using System;
using System.Data;
using System.Data.SqlClient;
using FrameWork.Core.Log;

namespace HYBY.Task.Repository.Dapper {

  /// <summary>
  /// <remarks>数据库连接管理</remarks>
  /// </summary>
  public class ConnnectionManager {
    /// <summary>
    /// 获取一个打开IDbConnection
    /// </summary>
    /// <param name="connectionString"></param>
    /// <returns></returns>
    public IDbConnection GetOpenConnection(string connectionString) {
      if (string.IsNullOrEmpty(connectionString)) {
        NLogUtil.Error(string.Format("{0} ConnectionString not exist!", connectionString), NLog.LogManager.GetCurrentClassLogger());
        throw new ApplicationException("ConnectionString not exist!");
      }
      return this.GetOpenConnection(null, connectionString);
    }

    private IDbConnection GetOpenConnection(IDbConnection sharedConnection, string connectionString) {
      if (sharedConnection != null) {
        if (sharedConnection.State == ConnectionState.Closed)
          sharedConnection.Open();
        return sharedConnection;
      }
      //扩展点，如果以后新的数据库连接，可以在这里进行扩展
      var connection = new SqlConnection(connectionString);
      connection.Open();
      return connection;
    }
  }
}
